package com.paco.study.cloud.code.service.impl;

import com.paco.study.cloud.code.dao.AuthCodeDao;
import com.paco.study.cloud.code.model.AuthCode;
import com.paco.study.cloud.code.service.AuthCodeService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private AuthCodeDao codeDao;

    @Override
    public String createCode(String email) {

//        随机6位验证码
        return RandomStringUtils.randomNumeric(6);

    }

    @Override
    public Integer validate(String email, String code) {
        //        验证验证码
        AuthCode authCode = codeDao.findByEmailAndCode(email, code);

        int result;
        if (authCode != null) {

//            失效时间
            if (authCode.getCreatetime() != null &&
                    authCode.getExpiretime() != null &&
                    !DateUtils.addMinutes(authCode.getCreatetime(), 6).after(authCode.getExpiretime())) {
                result = 2;
            } else {
                result = 0;
            }
        } else {
            result = 1;
        }

        return result;
    }

//    保存验证码
    @Override
    public void save(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);

        Date now = new Date();
        authCode.setCreatetime(now);
//        设置失效时间
        authCode.setExpiretime(DateUtils.addMinutes(now, 6));

        codeDao.saveAndFlush(authCode);
    }


}
